package com.powernode.config;

import cn.hutool.core.util.ObjectUtil;
import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @create: 2024/7/16
 * @author: gyhe10
 * @description: Feign拦截器。解决服务之间调用没有token的问题
 **/

@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 1 浏览器发送的请求会携带token
        // 获取当前请求的上下文对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 判断是否有上下文对象
        if (ObjectUtil.isNotNull(requestAttributes)) {
            // 获取请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 判断是否有请求对象
            if (ObjectUtil.isNotNull(request)) {
                // 获取请求头中的token，传递到下一个请求对象的请求头
                String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
                template.header(AuthConstants.AUTHORIZATION, authorizationValue);
                return;
            }
        }

        // 2 没有携带token的请求，如定时任务、监听任务产生的请求，设置一个固定值
        template.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "8bf0b3cb-086f-475b-b745-4068cd204234");
    }
}
